package com.taoyige;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.commons.lang.time.DateUtils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.preference.PreferenceManager;

import com.taoyige.bean.AccessInfo;
import com.taoyige.common.StringUtils;

/**
 * 应用程序配置类：用于保存用户相关信息及设置
 * @author peter
 * @version 1.0
 * @date 2014-11-12
 */
@SuppressLint("NewApi")
public class AppConfig {

	private final static String APP_CONFIG = "config";
	
	public static final String ALIPAY_CONFIG_PARTNER = "2088801569286184";
	public static final String ALIPAY_CONFIG_SELLER = "support@instreet.cn";
	public static final String ALIPAY_CONFIG_RSA_PRIVATE = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOJpHgND44u9rI1D"
																									+"RrExCvR8+vpXT78z+JzWnQpBfE+ZQtIXoXvRU6hXtYQdTCodX4DYXBMhkyz+4f+C"
																									+"VLTH6tBAYJAPiF8reK0gWRViNUuDiCoJkHTF2A3a6t5cl0J0D43/zO0gSP32K4hd"
																									+"yXFY0nC/+d4iEU6rmSBo/l4h1ESNAgMBAAECgYEAiR+4+alISv4ZX4T7b52QUPrQ"
																									+"1oXC2r6TOAoTGn8G1v6vpaaCOwdQb4iPevBzjJ41lUd0nHGdPYcxQRqiSss5vrte"
																									+"50I/8kVaqWcFoHVwp/gvZSCKYvSQZ0xFrQJrCPEWGO8sQkgcVpBliDs2JW5yxCT+"
																									+"8OTAnnljPJGueGvcsFECQQDxj4QpM0YDBCgmHKWdLWU4BF/nkN+BoXr4JRA5a+VP"
																									+"slymUGH2nRDQZqCu9I72hs4auotK/h7Tn3WuHSWP4yGvAkEA7/HEnFI7NDABmZMm"
																									+"Mqr9U+dJWKs5iIGfeKF48xsxNMc2Ugx9nbkKZgHWXgPO0yMxL0APP+kxEa0Bql/0"
																									+"yDB4gwJAFkfzm81D7vFKNsG7sPTH+lPE+NoPE6jua8cXaQR/wUslap3Ne27fZymg"
																									+"NqMOMMUca7C7Om6YL1LtCuNbXJtJtwJBAJAZ88kp/ZJfDmbsH7GoTVHZgow08O2R"
																									+"Y3OwDhJ6jzeyOGZYSAy0N5GBovt9b/YPmZdV8pKgeq6x52EqFbkwmv8CQQDOrYST"
																									+"s4gEFo7lXB4nQVKlqwNrNBLPwlsxkG2rJebmJH+lLKCA5xOBNWeZ8XZgUtG2QtnS"
																									+"dO0dEpiQUBY3YLxI";
	//商户公钥上传到支付宝生成的支付宝公钥
	public static final String ALIPAY_CONFIG_RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";

	
	public static final int PAY_PLATFFROM_ALIPAY= 2;
	public static final int PAY_PLATFFROM_WECHAT= 1;
	
	/** UNPAID(1),PAID(2),DELIVERED(3),CHECKED(4),CLOSED(5),DELETED(6),REFUND(7),REFUND_SUCCESS(8),RETURN_GOODS(9),RETURN_GOODS_SUCCESS(10);*/
	//未付款
	public static final int ORDER_UNPAID= 1;
	//已经付款
	public static final int ORDER_PAID= 2;
	//已经发货
	public static final int ORDER_DELIVERED= 3;
	//已经签收
	public static final int ORDER_CHECKED= 4;
	//订单关闭
	public static final int ORDER_CLOSED= 5;
	//订单删除
	public static final int ORDER_DELETED= 6;
	//退款中
	public static final int ORDER_REFUND= 7;
	//退款成功
	public static final int ORDER_REFUND_SUCCESS= 8;
	//退货中
	public static final int ORDER_RETURN_GOODS= 9;
	//退货成功
	public static final int ORDER_RETURN_GOODS_SUCCESS= 10;
	
	
	public static final int BADGE_NO= 1;
	public static final int BADGE_ORDER_NOPAID= 2;
	public static final int BADGE_ORDER_PAID= 3;
	
	public static final String LOGIN_TYPE= "login_type";
	public static final int LOGIN_TYPE_USER_AVATAR_BUTTON = 0;
	public static final int LOGIN_TYPE_USER_INDEX_BUY_BUTTON = 1;
	public static final int LOGIN_TYPE_USER_DETAIL_BUY_BUTTON = 2;
    
	public static final int LOGIN_OAUTH_WECHAT= 4;
	public static final int LOGIN_OAUTH_QQ = 3;
	public static final int LOGIN_OAUTH_WEIBO = 2;
	public static final int LOGIN_OAUTH_ALIPAY =1;
    
	public final static String CONF_APP_UNIQUEID = "APP_UNIQUEID";
	public final static String CONF_COOKIE = "cookie";
	

	 private static final String OAUTH_WEIBO_PREFERENCES_NAME = "taoyige_weibo_oauth";
	 private static final String OAUTH_QQ_PREFERENCES_NAME = "taoyige_qq_oauth";
	 private static final String OAUTH_ALIPAY_PREFERENCES_NAME = "taoyige_alipay_oauth";
	 private static final String KEY_UID           = "uid";
	 private static final String KEY_ACCESS_TOKEN  = "access_token";
	 private static final String KEY_EXPIRES_IN    = "expires_in";
	 private static final String KEY_EXPIRES_TIME    = "expires_time";
	    
	public final static String CONF_LOAD_IMAGE = "perf_loadimage";
	public final static String CONF_SCROLL = "perf_scroll";
	public final static String CONF_HTTPS_LOGIN = "perf_httpslogin";
	public final static String CONF_VOICE = "perf_voice";
	public final static String CONF_CHECKUP = "perf_checkup";
	
    public static final String APP_KEY_WEIBO      = "2266589330";
    public static final String APP_KEY_QQ="1103510626";
    public static final String APP_KEY_WECHAT="wxa2603e811ff54a52";
    public static final String APP_SECRET_WECHAT="c48da20e654b8311aeece66fb2e1155f";
	public static final int WX_MIN_SUPPORTED_VERSION = 0x21020001;// 最小支持的版本
	
	
    public static final String SCOPE_QQ = "all";
	
	public static final int OAUTH_ERROR = 0;
	public static final int OAUTH_RequestToken_ACCESS = 1;
	public static final int OAUTH_RequestToken_ERROR = 2;
	public static final int OAUTH_AccessToken_ACCESS = 3;
	public static final int OAUTH_AccessToken_ERROR = 4;
	public static final int OAUTH_AccessToken_EXPIRED = 5;
	
	
	
    /** 
     * 当前 DEMO 应用的回调页，第三方应用可以使用自己的回调页。
     * 
     * <p>
     * 注：关于授权回调页对移动客户端应用来说对用户是不可见的，所以定义为何种形式都将不影响，
     * 但是没有定义将无法使用 SDK 认证登录。
     * 建议使用默认回调页：https://api.weibo.com/oauth2/default.html
     * </p>
     */
    public static final String WEIBO_REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";

    /**
     * Scope 是 OAuth2.0 授权机制中 authorize 接口的一个参数。通过 Scope，平台将开放更多的微博
     * 核心功能给开发者，同时也加强用户隐私保护，提升了用户体验，用户在新 OAuth2.0 授权页中有权利
     * 选择赋予应用的功能。
     * 
     * 我们通过新浪微博开放平台-->管理中心-->我的应用-->接口管理处，能看到我们目前已有哪些接口的
     * 使用权限，高级权限需要进行申请。
     * 
     * 目前 Scope 支持传入多个 Scope 权限，用逗号分隔。
     * 
     * 有关哪些 OpenAPI 需要权限申请，请查看：http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI
     * 关于 Scope 概念及注意事项，请查看：http://open.weibo.com/wiki/Scope
     */
    public static final String SCOPE_WEIBO = 
            "email,direct_messages_read,direct_messages_write,"
            + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
            + "follow_app_official_microblog," + "invitation_write";
    
    
    
    
	public final static String SAVE_IMAGE_PATH = "save_image_path";
	@SuppressLint("NewApi")
	public final static String DEFAULT_SAVE_IMAGE_PATH = Environment.getExternalStorageDirectory()+ File.separator+ "taoyige"+ File.separator;
			
	private Context mContext;
	private AccessInfo accessInfo = null;
	private static AppConfig appConfig;

	public static AppConfig getAppConfig(Context context) {
		if (appConfig == null) {
			appConfig = new AppConfig();
			appConfig.mContext = context;
		}
		return appConfig;
	}

	/**
	 * 获取Preference设置
	 */
	public static SharedPreferences getSharedPreferences(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context);
	}

	/**
	 * 是否加载显示图片
	 */
	public static boolean isLoadImage(Context context) {
		return getSharedPreferences(context).getBoolean(CONF_LOAD_IMAGE, true);
	}

	public String getCookie() {
		return get(CONF_COOKIE);
	}

	    
	    /**
	     * 保存 Token 对象到 SharedPreferences。
	     * 
	     * @param context 应用程序上下文环境
	     * @param token   Token 对象
	     */
	    public  static void writeAccessToken(Context context, Integer auth_type,AccessInfo ac) {
	        if (null==context||null == auth_type || null ==ac) {
	            return;
	        }
	        SharedPreferences pref = null;
	        switch(auth_type){
	        case AppConfig.LOGIN_OAUTH_WEIBO:
	        	pref=context.getSharedPreferences(OAUTH_WEIBO_PREFERENCES_NAME, Context.MODE_APPEND);
	        	break;
	        case AppConfig.LOGIN_OAUTH_QQ:
	        	pref=context.getSharedPreferences(OAUTH_QQ_PREFERENCES_NAME, Context.MODE_APPEND);
	        	break;
	        case AppConfig.LOGIN_OAUTH_ALIPAY:
	        	pref=context.getSharedPreferences(OAUTH_ALIPAY_PREFERENCES_NAME, Context.MODE_APPEND);
	        	break;
	        }
	        
	          Editor editor = pref.edit();
	          editor.putString(KEY_UID, ac.getUid());
	          editor.putString(KEY_ACCESS_TOKEN, ac.getAccessToken());
	          if(auth_type==AppConfig.LOGIN_OAUTH_WEIBO){
	              editor.putLong(KEY_EXPIRES_TIME, ac.getExpiresIn());
	              editor.putLong(KEY_EXPIRES_IN, ac.getExpiresIn());
	          }else{
	        	  editor.putLong(KEY_EXPIRES_TIME, DateUtils.addSeconds(new Date(), ac.getExpiresIn().intValue()).getTime());
	              editor.putLong(KEY_EXPIRES_IN,ac.getExpiresIn());
	          }

	          editor.commit();

	    }

	    /**
	     * 从 SharedPreferences 读取 Token 信息。
	     * 
	     * @param context 应用程序上下文环境
	     * 
	     * @return 返回 Token 对象
	     */
	    public static  AccessInfo readAccessToken(Context context,Integer auth_type) {
	        if (null == context||null==auth_type) {
	            return null;
	        }
	        
	        AccessInfo token = new AccessInfo();
	        
	        SharedPreferences pref = null;
	        switch(auth_type){
	        case AppConfig.LOGIN_OAUTH_WEIBO:
	        	pref=context.getSharedPreferences(OAUTH_WEIBO_PREFERENCES_NAME, Context.MODE_APPEND);
	        	break;
	        case AppConfig.LOGIN_OAUTH_QQ:
	        	pref=context.getSharedPreferences(OAUTH_QQ_PREFERENCES_NAME, Context.MODE_APPEND);
	        	break;
	        case AppConfig.LOGIN_OAUTH_ALIPAY:
	        	pref=context.getSharedPreferences(OAUTH_ALIPAY_PREFERENCES_NAME, Context.MODE_APPEND);
	        	break;
	        }
	        
	        token.setUid(pref.getString(KEY_UID, null));
	        token.setAccessToken(pref.getString(KEY_ACCESS_TOKEN, null));
	        token.setExpiresTime(pref.getLong(KEY_EXPIRES_TIME, 0l));
	        token.setExpiresIn(pref.getLong(KEY_EXPIRES_IN, 0l));
	        return token;
	    }

	    /**
	     * 清空 SharedPreferences 中 Token信息。
	     * 
	     * @param context 应用程序上下文环境
	     */
	    public static  void clearOauth(Context context,Integer auth_type) {
	        if (null == context||null==auth_type) {
	            return;
	        }
	        SharedPreferences pref = null;
	        switch(auth_type){
	        case AppConfig.LOGIN_OAUTH_WEIBO:
	        	pref=context.getSharedPreferences(OAUTH_WEIBO_PREFERENCES_NAME, Context.MODE_APPEND);
	        	break;
	        case AppConfig.LOGIN_OAUTH_QQ:
	        	pref=context.getSharedPreferences(OAUTH_QQ_PREFERENCES_NAME, Context.MODE_APPEND);
	        	break;
	        case AppConfig.LOGIN_OAUTH_ALIPAY:
	        	pref=context.getSharedPreferences(OAUTH_ALIPAY_PREFERENCES_NAME, Context.MODE_APPEND);
	        	break;
	        }
	        Editor editor = pref.edit();
	        editor.clear();
	        editor.commit();
	    }
	    
	    /**
	     * 清空 SharedPreferences 中 Token信息。
	     * 
	     * @param context 应用程序上下文环境
	     */
	    public static  void clearOauthAll(Context context) {
	        if (null == context) {
	            return;
	        }
	       clearOauth(context, AppConfig.LOGIN_OAUTH_WEIBO);
	       clearOauth(context, AppConfig.LOGIN_OAUTH_QQ);
	       clearOauth(context, AppConfig.LOGIN_OAUTH_ALIPAY);
	    }
	    
	    

	public String get(String key) {
		Properties props = get();
		return (props != null) ? props.getProperty(key) : null;
	}

	public Properties get() {
		FileInputStream fis = null;
		Properties props = new Properties();
		try {
			// 读取files目录下的config
			// fis = activity.openFileInput(APP_CONFIG);

			// 读取app_config目录下的config
			File dirConf = mContext.getDir(APP_CONFIG, Context.MODE_PRIVATE);
			fis = new FileInputStream(dirConf.getPath() + File.separator
					+ APP_CONFIG);

			props.load(fis);
		} catch (Exception e) {
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return props;
	}

	private void setProps(Properties p) {
		FileOutputStream fos = null;
		try {
			// 把config建在files目录下		// fos = activity.openFileOutput(APP_CONFIG, Context.MODE_PRIVATE);

			// 把config建在(自定义app_config的目录下
			File dirConf = mContext.getDir(APP_CONFIG, Context.MODE_PRIVATE);
			File conf = new File(dirConf, APP_CONFIG);
			fos = new FileOutputStream(conf);

			p.store(fos, null);
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}

	public void set(Properties ps) {
		Properties props = get();
		props.putAll(ps);
		setProps(props);
	}

	public void set(String key, String value) {
		Properties props = get();
		props.setProperty(key, value);
		setProps(props);
	}

	public void remove(String... key) {
		Properties props = get();
		for (String k : key)
			props.remove(k);
		setProps(props);
	}
}
